using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace TMS_Demo.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class OpenidController : ControllerBase
    {
        // 获取 OpenId
        [HttpGet("{code}")]
        public string getOpenId(string code)
        {
            var _httpClient = new HttpClient();

            var appId = "wxebadd5f2ffeb172c";
            var secret = "bdc8e70ee413e4a7a38f132491f95256";

            string serviceAddress = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
            request.Method = "GET";
            request.ContentType = "textml;charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, System.Text.Encoding.UTF8);
            string retString = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();
            var obj = new
            {
                data = retString,
                Success = true
            };
            Formatting microsoftDataFormatSettings = default(Formatting);
            string result = JsonConvert.SerializeObject(obj, microsoftDataFormatSettings);

            // 删除 session_key ，因为用不上
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);

            var tmp = jo["data"].ToString();

            JObject jo2 = (JObject)JsonConvert.DeserializeObject(tmp);

            jo2.Remove("session_key");

            return jo2.ToString();
        }
    }
}